package com.contest.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.contest.entity.RaceInfo;
import com.contest.service.RaceInfoService;
import com.contest.util.*;
import com.contest.util.DateUtil;
import com.contest.ws.WebSocketSessionManager;
import com.xiaoleilu.hutool.date.*;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.contest.entity.RoomInfo;
import com.contest.service.RoomInfoService;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.socket.WebSocketSession;

import javax.servlet.http.HttpServletRequest;


/**
 * @author yfl
 * @email 617823298@qq.com
 * @date 2018-01-10 14:54:24
 */

@Controller
@RequestMapping("/roomInfo")
public class RoomInfoController {

    @Autowired
    RoomInfoService roomInfoService;
    @Autowired
    RaceInfoService raceInfoService;
    @Autowired
    IdWorker idWorker;
    private Logger logger = LoggerFactory.getLogger(RoomInfoController.class);
    @RequestMapping("/list")
    @ResponseBody
    public PageUtils list(@RequestParam Map<String, Object> param) {
        int page = Integer.parseInt(param.get("page").toString());
        int rows = Integer.parseInt(param.get("rows").toString());
        Page<RoomInfo> mPage = new Page<RoomInfo>(page, rows);
        param.remove("page");
        param.remove("rows");
        Wrapper<RoomInfo> w = new EntityWrapper<>();
        Set<String> keys = param.keySet();
        for (String key : keys) {
            Object value = param.get(key);
            if (value != null && !"".equals(value)) {
                w.like(key, value.toString());
            }
        }
        mPage = roomInfoService.selectPage(mPage,w);
        return new PageUtils(mPage.getRecords(), mPage.getTotal());
    }

    @PostMapping("/save")
    @ResponseBody
    public R save(HttpServletRequest request, @RequestParam("roomPic") CommonsMultipartFile roomPic, RoomInfo roomInfo) {
        String saveName = null;
        if (roomPic != null && !roomPic.getOriginalFilename().equals("")) {
            saveName = FileUtil.uploadFile(request, roomPic);
            roomInfo.setFdPic(saveName);
        }
        roomInfo.setFdId(idWorker.nextId() + "");
        if (roomInfoService.insert(roomInfo)) {
            return R.ok("操作成功!");
        } else {
            return R.error("操作失败");
        }
    }

    @GetMapping("/edit/{fdId}")
    public String edit(Model model, @PathVariable("fdId") String fdId) {
        RoomInfo roomInfo = roomInfoService.selectById(fdId);
        model.addAttribute("roomInfo", roomInfo);
        return "roomInfo/edit";
    }

    @PostMapping("/remove")
    @ResponseBody
    public R remove(@RequestParam("ids[]") String[] ids) {
        List<String> fdIds = new ArrayList<String>();
        for (String id : ids) {
            fdIds.add(id);
        }
        if (roomInfoService.deleteBatchIds(fdIds)) {
            return R.ok("删除成功");
        } else {
            return R.error(-1, "删除失败!");
        }
    }

    @PostMapping("/update")
    @ResponseBody
    public R update(HttpServletRequest request, @RequestParam("roomPic") CommonsMultipartFile roomPic, RoomInfo roomInfo) {
        String saveName = null;
        if (roomPic != null && !roomPic.getOriginalFilename().equals("")) {
            saveName = FileUtil.uploadFile(request, roomPic);
            roomInfo.setFdPic(saveName);
        }
        if (roomInfoService.updateResult(roomInfo)) {
            return R.ok("更新成功!");
        } else {
            return R.error(-1, "更新失败!");
        }
    }

    @ResponseBody
    @RequestMapping("/client/raceRoomList")
    public R raceRoomList(String raceId) throws ParseException {
        WebSocketSessionManager socketSessionManager = WebSocketSessionManager.getInstance();
        if (socketSessionManager.getSessionMap() == null) {
            Map<String, Map<String, List<WebSocketSession>>> sessionMap = Collections.synchronizedMap(new HashMap<String, Map<String, List<WebSocketSession>>>());
            socketSessionManager.setSessionMap(sessionMap);
        }
        RaceInfo raceInfo = raceInfoService.selectById(raceId);
        List<Map<String, Object>> ls = new ArrayList<>();
        if (raceInfo != null) {
            Map<String, List<WebSocketSession>> roomSession = socketSessionManager.getSessionMap().get(raceInfo.getFdId());
            if (roomSession == null) {
                roomSession = Collections.synchronizedMap(new HashMap<String, List<WebSocketSession>>());
                EntityWrapper<RoomInfo> roomInfoEntityWrapper = new EntityWrapper<RoomInfo>();
                logger.info("====================="+raceInfo.getFdId());
                roomInfoEntityWrapper.addFilter("fd_race_id={0}", raceInfo.getFdId());
                List<RoomInfo> rooms = roomInfoService.selectList(roomInfoEntityWrapper);
                for (int i = 0; i < rooms.size(); i++) {
                    List<WebSocketSession> socketSessions = roomSession.get(rooms.get(i).getFdName());
                    if (socketSessions == null) {
                        socketSessions = Collections.synchronizedList(new ArrayList<WebSocketSession>());
                        roomSession.put(rooms.get(i).getFdName(), socketSessions);
                        socketSessionManager.getSessionMap().put(raceInfo.getFdId(), roomSession);
                        Map<String, Object> online = new HashMap<>();
                        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        online.put("roomName",rooms.get(i).getFdName());
                        online.put("onlineNum",0);
                        online.put("vs_a",rooms.get(i).getFdClanAName());
                        online.put("vs_b",rooms.get(i).getFdClanBName());
                        online.put("limit_num",rooms.get(i).getFdNum());
                        online.put("roomId",rooms.get(i).getFdId());
                        Long start = (new Date()).getTime();
                        Long end = sdf2.parse(rooms.get(i).getFdEndTime()).getTime();
                        if(end > start){
                            String result = DateUtil.formatTime(end - start);
                            online.put("subtime",result);
                        }else{
                            online.put("subtime","0");
                        }
                        ls.add(online);
                    }
                }
            } else {
                Set<String> roomNames = roomSession.keySet();
                for (String roomName : roomNames) {
                    Wrapper<RoomInfo> w = new EntityWrapper<>();
                    w.addFilter("fd_race_id={0}",raceId);
                    w.and("fd_result != {} and fd_is_settle != {1}",0,1);
                    List<RoomInfo> list = roomInfoService.selectList(w);
                    if(list.size() > 0){
                        //RoomInfo r = (RoomInfo) list.get(0);

                        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm:ss");
                        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        for(RoomInfo r : list) {
                            Map<String, Object> online = new HashMap<>();
                            online.put("roomName", r.getFdName());
                            online.put("onlineNum", roomSession.get(roomName).size());
                            online.put("vs_a", r.getFdClanAName());
                            online.put("vs_b", r.getFdClanBName());
                            online.put("limit_num", r.getFdNum());
                            online.put("roomId", r.getFdId());
                            Long start = (new Date()).getTime();
                            Long end = sdf2.parse(r.getFdEndTime()).getTime();

                            if (end > start) {
                                String result = DateUtil.formatTime(end - start);
                                online.put("subtime", result);
                            } else {
                                online.put("subtime", "0");
                            }
                            ls.add(online);
                        }
                    }
                }
            }
            return R.ok(ls);
        } else {
            return R.error("赛事不存在");
        }
    }


    @RequestMapping("/client/getRoomInfoByID")
    @ResponseBody
    public R getRoomInfoByID(String id){
        RoomInfo roomInfo = roomInfoService.selectById(id);
        String endTime = roomInfo.getFdEndTime();
        long end = com.xiaoleilu.hutool.date.DateUtil.parse(endTime, "yyyy-MM-dd HH:mm:ss").getTime();
        long current = System.currentTimeMillis();
        if(end >= current) {
            return R.ok(roomInfo);
        }else{
            return R.error("比赛已结束");
        }
    }

    @RequestMapping("/webLeagueInfo")
    @ResponseBody
    public R getWebLeagueInfo(){
        List<RoomInfo> roomInfos = roomInfoService.getList();
        return R.ok(roomInfos);
    }

}
